package nio;

import java.nio.Buffer;
import java.nio.IntBuffer;

/**
 * User: Administrator
 * Date: 2021/3/30
 * Time: 16:08
 * Description:
 * Buffer类的使用
 */
public class UseBuffer {

    public static void main(String[] args) {
        IntBuffer test = createTest();
        printInfo(test);
        //写
        for (int i = 0; i < 5; i++) {
            test.put(i);
        }
        printInfo(test);
        //写 转 读 flip后才能读
        test.flip();
        printInfo(test);
        //读
        for (int i = 0; i < 3; i++) {
            int i1 = test.get();
            System.out.println(i1);
        }
        printInfo(test);

        //重复读
        test.rewind();
        printInfo(test);
        for (int i = 0; i < 3; i++) {
            int i1 = test.get();
            System.out.println(i1);
        }
        printInfo(test);

        //清空buffer 进入读模式
        test.clear();
        printInfo(test);
    }

    public static IntBuffer createTest() {
        return IntBuffer.allocate(20);
    }

    public static void printInfo(IntBuffer intBuffer) {
        System.out.println("capacity === " + intBuffer.capacity());
        System.out.println("position === " + intBuffer.position());
        System.out.println("limit === " + intBuffer.limit());
        System.out.println("mark === " + intBuffer.mark());
    }
}
